<?php
/**
 * Created by PhpStorm.
 * User: 93933
 * Date: 2021/11/19
 * Time: 11:50
 */

namespace catchAdmin\logistics\controller;


use catcher\base\CatchRequest as Request;
use catcher\CatchAuth;
use catcher\CatchResponse;
use catcher\base\CatchController;
use think\Response;
use think\facade\Db;
use catcher\Code;
use catchAdmin\logistics\model\Task as TaskModel;
use catchAdmin\logistics\model\Order as OrderModel;

class Shimei extends CatchController
{
    private $comKey = 'ltdjq';//公司key
    private $comSecret = '1128E3BE-5B73-40BF-BA05-E20DD62F8F82';//公司秘钥

    protected $taskModel;

    /**
     *
     * @time 2021/11/08 11:25
     * @param OrderModel $orderModel
     * @return mixed
     */
    public function __construct(TaskModel $taskModel, OrderModel $orderModel)
    {
        $this->taskModel = $taskModel;
        $this->orderModel = $orderModel;
    }

    /**
     * 列表
     *
     * @time 2020年01月09日
     * @param CatchRequest $request
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     */
    public function index(): \think\response\Json
    {
        return CatchResponse::paginate($this->orderModel->getList());
    }

    /**
     *
     * @time 2021/11/08 11:25
     * @return Response
     */
    public function taskInfo(Request $request,CatchAuth $auth)
    {
        try {
            $user = $auth->user();
            $task_no = $request->post('task_no');
            $info = $this->taskModel
                ->field('id,task_no,status')
                ->where([['del_status', '=', 0], ['task_no', '=', $task_no], ['tenant_id','=',$user['tenant_id']]])
                ->order('id', 'desc')
                ->find();

            $list = $this->orderModel->getList()->toArray();
            return CatchResponse::success(['info' => $info, 'list' => $list], '操作成功', 10000);

        } catch (\Exception $exception) {
            return CatchResponse::fail($exception->getMessage(), Code::FAILED);

        }
    }


    /**
     *
     * @time 2021/11/08 11:25
     * @return Response
     */
    public function prepareOrderlist(Request $request,CatchAuth $auth)
    {
        try {
            $user = $auth->user();
            $task_no = $request->post('taskNo');
            $list = $this->orderModel->field('id,orderId,task_no,contactName,logistics_status')
                ->whereOr([[['deleteStatus', '=', 0], ['status', '=', 0], ['logistics_status', '=', 0], ['tenant_id','=',$user['tenant_id']]], [['deleteStatus', '=', 0], ['status', '=', 0], ['task_no', '=', $task_no], ['tenant_id','=',$user['tenant_id']]]])
                ->order('id', 'desc')
                ->select()->toArray();
            if ($list) {
                return CatchResponse::success($list, '操作成功', 10000);
            } else {
                return CatchResponse::success([], '操作成功', 10000);
            }
        } catch (\Exception $exception) {
            return CatchResponse::fail($exception->getMessage(), Code::FAILED);

        }
    }

    /**
     * 加入批次订单
     * @time 2021/11/08 11:25
     * @return Response
     */
    public function addOrder(Request $request)
    {
        try {
            $orders = $request->post('orders');
            $task_no = $request->post('task_no');
            $success = 0;
            foreach ($orders as $key => $value) {
                $res = $this->orderModel->where(['orderId' => $value])->save(['task_no' => $task_no, 'logistics_status' => 4, 'modifyTime' => date('Y-m-d H:i:s')]);
                if ($res) {
                    $success++;
                }

            }
            return CatchResponse::success([], '已成功操作' . $success . '项', 10000);


        } catch (\Exception $exception) {

            return CatchResponse::fail($exception->getMessage(), Code::FAILED);

        }
    }

    /**
     * 推送批次订单
     * @time 2021/11/08 11:25
     * @return Response
     */
    public function pushOrder(Request $request)
    {
        try {
            $orders = $request->post('orders');
            $task_no = $request->post('task_no');
            $res = $this->pushTaskNoDg($task_no, $orders, 0);

            return CatchResponse::success([], $res['msg'], 10000);

        } catch (\Exception $exception) {

            return CatchResponse::fail($exception->getMessage(), Code::FAILED);

        }
    }

    /**
     * 撤销订单  调用时美接口撤销订单
     * @time 2021/11/08 11:25
     * @return Response
     */
    public function cancelOrder(Request $request)
    {
        try {
            $orders = $request->post('orders');
            $task_no = $request->post('task_no');
            $res = $this->cancelOrderDg($task_no, $orders, 0);

            return CatchResponse::success([], $res['msg'], 10000);

        } catch (\Exception $exception) {

            return CatchResponse::fail($exception->getMessage(), Code::FAILED);

        }
    }

    /**
     * 移除订单  订单移出当前批次
     * @time 2021/11/08 11:25
     * @return Response
     */
    public function moveOrder(Request $request)
    {
        try {
            $orders = $request->post('orders');
            $task_no = $request->post('task_no');
            $success = 0;
            foreach ($orders as $key => $value) {
                $res = Db::table('db_customs_order')->where(['orderId' => $value, 'task_no' => $task_no])->save(array('task_no' => '', 'logistics_status' => 0, 'modifyTime' => date('Y-m-d H:i:s')));
                if ($res) {
                    $success++;
                }

            }
            return CatchResponse::success([], '已成功操作' . $success . '项', 10000);


        } catch (\Exception $exception) {

            return CatchResponse::fail($exception->getMessage(), Code::FAILED);

        }
    }

    /**
     * 完成批次
     * @time 2021/11/08 11:25
     * @return Response
     */
    public function finishTask(Request $request)
    {
        try {
            $task_nos = $request->post('task_nos');
            $datetimeStamp = date('YmdHis', time());
            $success = 0;
            $errmsg = '';
            foreach ($task_nos as $key => $value) {
                //是否有没有推送的订单
                $list = Db::table('db_customs_order')->where(['task_no' => $value, 'logistics_status' => ['neq', 2]])->select();
                if ($list) {
                    $errmsg = '批次号' . $value . '有未推送的订单';
                    break;
                }

                $res = $this->finishTaskDo($datetimeStamp, $value);
                if ($res['status'] == 100) {
                    Db::table('db_task_no')->where(['task_no' => $value])->save(['status' => 1, 'modify_time' => time()]);
                    Db::table('db_customs_order')->where(['task_no' => $value])->save(['logistics_status' => 1, 'error_msg' => '', 'modifyTime' => date('Y-m-d H:i:s')]);
                    $success++;
                }
            }

            return CatchResponse::success([], '已成功操作' . $success . '项。' . $errmsg, 10000);

        } catch (\Exception $exception) {

            return CatchResponse::fail($exception->getMessage(), Code::FAILED);

        }
    }

    /**
     * 撤销批次
     * @time 2021/11/08 11:25
     * @return Response
     */
    public function cancelTask(Request $request)
    {
        try {
            $task_nos = $request->post('task_nos');
            $datetimeStamp = date('YmdHis', time());
            $success = 0;
            foreach ($task_nos as $key => $value) {
                $res = $this->cancelTaskDo($datetimeStamp, $value);
                if ($res['status'] == 100) {
                    Db::table('db_task_no')->where(['task_no' => $value])->save(['del_status' => 1, 'modify_time' => time()]);
                    Db::table('db_customs_order')->where(['task_no' => $value])->save(['task_no' => '', 'error_msg' => '', 'logistics_status' => 0, 'modifyTime' => date('Y-m-d H:i:s')]);
                    $success++;
                }
            }
            return CatchResponse::success([], '已成功操作' . $success . '项', 10000);

        } catch (\Exception $exception) {

            return CatchResponse::fail($exception->getMessage(), Code::FAILED);

        }
    }

    /**
     * 完成批次接口
     * @time 2021/11/08 11:25
     * @return Response
     */
    public function finishTaskDo($datetimeStamp, $taskNo)
    {
        $comKey = $this->comKey;//公司key
        $comSecret = $this->comSecret;//公司秘钥
        $sdkToken = md5($comKey . $taskNo . $datetimeStamp . $comSecret);
        $url = 'https://cbe.haoyunzg.com/sdk/sale/setCbeLogisticsTaskComplete/' . $taskNo;
        //$url="http://q.qekj.net/appShop.php/Home/Applet/testxxx.html";
        $result_json = $this->Curl($url, '', 'POST', $sdkToken);
        $result = json_decode($result_json, true);
        if ($result && $result['Status'] == 100) {
            //调用批次完成接口
            $res = ['status' => 100, 'msg' => '完成批次成功'];
        } else {
            $res = ['status' => 109, 'msg' => '完成批次失败'];
        }
        return $res;
    }

    /**
     * 撤销批次接口
     * @time 2021/11/08 11:25
     * @return Response
     */
    public function cancelTaskDo($datetimeStamp, $taskNo)
    {
        $comKey = $this->comKey;//公司key
        $comSecret = $this->comSecret;//公司秘钥
        $sdkToken = md5($comKey . $taskNo . $datetimeStamp . $comSecret);
        //$url="http://q.qekj.net/appShop.php/Home/Applet/testxxx.html";
        $url = 'https://cbe.haoyunzg.com/sdk/sale/cancleCbeLogisticsTask/' . $taskNo;
        $result_json = $this->Curl($url, '', 'POST', $sdkToken);
        $result = json_decode($result_json, true);
        if ($result && $result['Status'] == 100) {
            //调用批次完成接口
            $res = ['status' => 100, 'msg' => '撤销批次成功'];
        } else {
            $res = ['status' => 109, 'msg' => '撤销批次失败'];
        }
        return $res;
    }

    /**
     * 递归推送订单
     * @time 2021/11/08 11:25
     * @return Response
     */
    public function pushTaskNoDg($taskNo, $orders, $success)
    {
        $orderId = array_shift($orders);
        $datetimeStamp = date('YmdHis', time());
        $re = $this->addOrderDo($taskNo, $orderId, $datetimeStamp);
        if ($re['status'] === 100) {
            Db::table('db_customs_order')->where(['orderId' => $orderId])->save(['logistics_status' => 2, 'modifyTime' => date('Y-m-d H:i:s'), 'error_msg' => '']);
            $success++;
            if (count($orders) > 0) {
                return $this->pushTaskNoDg($taskNo, $orders, $success);

            } else {
                return ['status' => 100, 'msg' => '已成功操作' . $success . '项'];
            }
        } elseif ($re['status'] === 200) {
            if (count($orders) > 0) {
                return $this->pushTaskNoDg($taskNo, $orders, $success);

            } else {
                return ['status' => 100, 'msg' => '已成功操作' . $success . '项'];
            }
        } else {
            Db::table('db_customs_order')->where(['orderId' => $orderId])->save(['logistics_status' => 3, 'modifyTime' => date('Y-m-d H:i:s'), 'error_msg' => $re['msg']]);
            if (count($orders) > 0) {
                return $this->pushTaskNoDg($taskNo, $orders, $success);

            } else {
                return ['status' => 100, 'msg' => '已成功操作' . $success . '项'];
            }
        }
    }

    /**
     * 推送订单接口
     * @time 2021/11/08 11:25
     * @return Response
     */
    public function addOrderDo($task_no, $orderId, $datetimeStamp)
    {
        $all_data = [];
        $info = Db::table('db_customs_orderlist')->where(['orderId' => $orderId, 'deleteStatus' => 0, 'status' => 0])->select();
        $order = Db::table('db_customs_order')->where(['orderId' => $orderId, 'deleteStatus' => 0])->find();
        //不是加入批次和推送失败状态的跳过
        if ($order['logistics_status'] !== 4 && $order['logistics_status'] !== 3) {
            return ['status' => 200, 'msg' => '批次添加订单成功'];
        }

        $detail = explode('-', $order['contactAddr']);
        $comKey = $this->comKey;
        $comSecret = $this->comSecret;//公司秘钥
        $barcodes = [];
        $productName = [];
        $snum = 0;
        $NetWeight = 0;
        foreach ($info as $k => $v) {
            $data['weight'] = $v['spec_qty'];//$v['weight'];
            $data['count'] = (int)$v['num'] * $v['spec_qty'];// $v['num'];
            $data['barCode'] = $v['barcode'];//'1';//
            $data['Tex'] = 0;
            $data['Price'] = round($v['price'] / $v['spec_qty'], 2);
            $snum += $data['count'];
            $NetWeight += $v['weight'] * $data['count'];
            $all_data['orderGoods'][] = $data;
            $barcodes[] = $data['barCode'];
            $productName[] = $v['productName'];
        }
        $all_data['taskNo'] = $task_no;
        $all_data['comKey'] = $comKey;
        $all_data['datetimeStamp'] = $datetimeStamp;
        $all_data['consignee'] = $order['contactName'];//'测试';//
        $all_data['consigneeAddress'] = $order['contactAddr'] . $order['detailAddr'];//"南京";//
        $all_data['insuredFee'] = $order['tax'];
        $all_data['consigneeTelephone'] = $order['contactMobile'];//"15195936366";//
        $all_data['billNo'] = $order['payOrderNo'];
        $all_data['packNo'] = 1;
        $all_data['orderNo'] = $order['orderId'];
        $all_data['Province'] = $detail[0];
        $all_data['City'] = $detail[1];
        $all_data['Area'] = $detail[2];
        $all_data['note'] = implode(',', $productName);
        $all_data['weight'] = $NetWeight;//4;
        $all_data['goodCount'] = $snum;
        $all_data['freight'] = $order['distributionfee'];
        $all_data['goodsInfo'] = implode(',', $barcodes);//商品条形码
        $all_data['consigneeIdentity'] = $order['ConsigneeCode'];
        $all_data['payNo'] = $order['payOrderNo'];
        $all_data['ZipCode'] = $order['postcode'];
        $all_data = json_encode($all_data, JSON_UNESCAPED_UNICODE);
        //$url = 'http://cbetest.haoyunzg.com/Sdk/Sale/addTaskOrder';//测试
        $url = 'https://cbe.haoyunzg.com/sdk/sale/addTaskOrder';//正式
        //$url="http://q.qekj.net/appShop.php/Home/Applet/testxxx.html";
        $sdkToken = md5($comKey . $task_no . $datetimeStamp . $comSecret);
        $result = $this->Curl($url, $all_data, 'POST', $sdkToken);
        $result = json_decode($result, true);

        if ($result['Status'] != 100) {
            $data = ['status' => 102, 'msg' => $result['Msg']];

        } else {
            $data = ['status' => 100, 'msg' => '批次添加订单成功'];

        }
        return $data;
    }

    /**
     * 递归撤销订单
     * @time 2021/11/08 11:25
     * @return Response
     */
    public function cancelOrderDg($taskNo, $orders, $success)
    {
        $orderId = array_shift($orders);
        $datetimeStamp = date('YmdHis', time());
        $re = $this->cancelOrderDo($taskNo, $datetimeStamp, $orderId);
        if ($re['status'] === 100) {
            Db::table('db_customs_order')->where(['orderId' => $orderId])->save(['error_msg' => '', 'task_no' => '', 'logistics_status' => 0, 'modifyTime' => date('Y-m-d H:i:s')]);
            $success++;
            if (count($orders) > 0) {
                return $this->cancelOrderDg($taskNo, $orders, $success);

            } else {
                return ['status' => 100, 'msg' => '已成功操作' . $success . '项'];
            }
        } else {
            Db::table('db_customs_order')->where(['orderId' => $orderId])->save(['error_msg' => $re['msg'], 'modifyTime' => date('Y-m-d H:i:s')]);

            if (count($orders) > 0) {
                return $this->cancelOrderDg($taskNo, $orders, $success);

            } else {
                return ['status' => 100, 'msg' => '已成功操作' . $success . '项'];
            }
        }
    }

    /**
     * 撤销订单接口
     * @time 2021/11/08 11:25
     * @return Response
     */
    public function cancelOrderDo($taskNo, $datetimeStamp, $orderNO)
    {
        $comKey = $this->comKey;//公司key
        $comSecret = $this->comSecret;//公司秘钥
        $sdkToken = md5($comKey . $taskNo . $datetimeStamp . $comSecret);
        $url = 'https://cbe.haoyunzg.com/Sdk/Sale/cancleOrder/' . $taskNo . '?orderNO=' . $orderNO . '&comKey=' . $comKey . '&DatetimeStamp=' . $datetimeStamp;
        //$url="http://q.qekj.net/appShop.php/Home/Applet/testxxx.html";
        $result_json = $this->Curl($url, json_encode([]), 'POST', $sdkToken);
        $result = json_decode($result_json, true);
        if ($result && $result['Status'] == 100) {
            //调用批次完成接口
            $res = ['status' => 100, 'msg' => '取消订单成功'];
        } else {
            $res = ['status' => 109, 'msg' => '取消订单失败'];
        }
        return $res;
    }

    public function modifyInfo(Request $request): Response
    {
        try {

            $orders = $request->post('orders');
            $list = Db::table('db_customs_order')
                ->field('orderId,task_no')
                ->where([['orderId', 'in', $orders]])
                ->select();
            foreach ($list as $key => $vo) {
                $res = $this->orderQuery($vo['orderId'], $vo['task_no']);
                if ($res['Status'] === 100) {
                    $data = [];
                    $data['bill_no'] = $res['Data']['logisticsNo'];
                    $data['express_company'] = $res['Data']['ExpressCompany'];
                    $data['express_no'] = $res['Data']['ExpressNo'];
                    $data['error_msg'] = '已更新物流信息';
                    Db::table('db_customs_order')->where(['orderId' => $vo['orderId']])->save($data);

                } else {
                    Db::table('db_customs_order')->where(['orderId' => $vo['orderId']])->save(['error_msg' => $res['Msg']]);

                }
            }
            return CatchResponse::success([], '操作成功', 10000);
        } catch (\Exception $exception) {
            return CatchResponse::fail($exception->getMessage(), Code::FAILED);

        }
    }

    //批次列表
    public function taskList(Request $request): Response
    {
        return CatchResponse::paginate($this->taskModel->getList());
    }

    //添加批次
    public function addTask(Request $request,CatchAuth $auth)
    {

        $whKey = $request->post('warehouse');
        if ($whKey == 'ltxgck1') {
            $memo = '龙潭香港仓库1';
        } else if ($whKey == 'njbsqck') {
            $memo = '南京保税区仓库';
        } else if ($whKey == 'ningboLT') {
            $memo = '龙潭宁波保税区仓库';
        } else if ($whKey == 'taizhoubsq') {
            $memo = '泰州保税仓';
        }
        //$memo = $request->post('memo');
        $taskNo = 'ltdjqDJQ' . date('YmdHis', time()) . rand(10, 99);
        $datetimeStamp = date('YmdHis', time());
        $result = $this->taskAddDo($taskNo, $datetimeStamp, $whKey, $memo);
        if ($result['status'] === 100) {
            $user = $auth->user();
            $data = array(
                'task_no' => $taskNo,
                'time' => time(),
                'tenant_id' => $user['tenant_id'],
                'warehouse' => $whKey
            );
            $res = Db::table('db_task_no')->insert($data);
            if ($res) {
                return CatchResponse::success([], '操作成功', 10000);
            } else {
                return CatchResponse::fail('操作失败', Code::FAILED);
            }
        } else {
            return CatchResponse::fail($result['msg'], Code::FAILED);
        }
    }

    public function taskAddDo($taskNo, $datetimeStamp, $whKey, $memo = '')
    {
        $comKey = $this->comKey;//公司key
        $comSecret = $this->comSecret;//公司秘钥
        $sdkToken = md5($comKey . $taskNo . $datetimeStamp . $comSecret);
        //$url = "https://cbe.haoyunzg.com/sdk/sale/addCbeLogisticsTask";
        //$url = "http://cbetest.haoyunzg.com/sdk/sale/addCbeLogisticsTask";//测试
        $url = "https://cbe.haoyunzg.com/sdk/sale/addCbeLogisticsTask";//正式
        $data = array();
        $data['taskNo'] = $taskNo;
        $data['comKey'] = $comKey;
        $data['memo'] = $memo;
        $data['whKey'] = $whKey;//仓库key
        $data['datetimeStamp'] = $datetimeStamp;
        $result_json = $this->Curl($url, json_encode($data, JSON_UNESCAPED_UNICODE), 'POST', $sdkToken);
        $result = json_decode($result_json, true);
        if ($result && $result['Status'] == 100) {
            //调用批次完成接口
            $res = ['status' => 100, 'msg' => '创建批次成功'];
        } else {
            $res = ['status' => 109, 'msg' => $result['Msg']];
        }
        return $res;
    }


    //订单查询
    public function orderQuery($orderNo, $taskNo)
    {
        $datetimeStamp = date('YmdHis');
        $comKey = $this->comKey;//公司key
        $comSecret = $this->comSecret;//公司秘钥
        $sdkToken = md5($comKey . $taskNo . $datetimeStamp . $comSecret);
        $url = "https://cbe.haoyunzg.com/Sdk/Sale/orderByNo?orderNO=" . $orderNo;
        //$url="http://q.qekj.net/appShop.php/Home/Applet/testxxx.html";
        $result = json_decode($this->Curl($url, '', 'GET', $sdkToken), true);
        return $result;
    }

    public function Curl($url, $data = null, $method, $sdkToken = '')
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            'Content-Type: application/json; charset=utf-8',
            'Accept: application/json',
            'Cache-Control: no-cache',
            'Pragma: no-cache',
            'sdkToken: ' . $sdkToken
        ));
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $tmpInfo = curl_exec($ch);
        $errorno = curl_errno($ch);
        if ($errorno) {
            return $errorno;
        } else {
            return $tmpInfo;
        }
    }


}